<template>
  <div class="pay">
    <div class="d-flex flex-wrap space-between">
      <div class="grid">
        <div class="header">
          账户信息
        </div>
        <div class="inner">
          <div class="info fs14">
            <div class="account">账号：{{ this.$store.state.username }}</div>
            <!-- <div class="level d-flex space-between">
              <span>等级：{{ account.level }}</span>
              <span style="display: none">
                <el-button type="warning" size="mini">升级</el-button>
              </span>
            </div> -->
            <div class="balance d-flex space-between">
              <span>余额：{{ account.balance }} 元</span>
            </div>
          </div>
        </div>
      </div>
      <div class="grid">
        <div class="header">余额充值</div>
        <div class="inner">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="在线充值" name="first">
              <el-form :model="payForm" ref="payForm" :rules="payFormRules" label-width="93px">
                <el-form-item label="充值金额：" prop="amount">
                  <el-input v-model="payForm.amount" type="number" :min="0.01" placeholder="输入充值金额（元）"></el-input>
                </el-form-item>
                <el-form-item label="实际充值：">
                  <span>￥ {{ payForm.amount }} 元</span>
                  <span style="color:red;margin-left:10px">（最低充值 0.01 元起）</span>
                </el-form-item>
                <el-form-item label="充值说明：">
                  <div v-html="rechargeDesc"></div>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="pay('payForm')">立即充值</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <!-- <el-tab-pane label="一卡通充值" name="second">一卡通充值内容</el-tab-pane> -->
          </el-tabs>
        </div>
      </div>
      <div class="grid">
        <div class="header">充值记录</div>
        <div class="inner">
          <el-form :inline="true" :model="queryInfo" class="demo-form-inline">
            <el-form-item label="">
              <el-input v-model="queryInfo.query" type="text" placeholder="支付单号" clearable @clear="getPayRecord"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
            </el-form-item>
          </el-form>
          <!-- 订单列表 -->
          <el-table
            :data="payRecord"
            border
            style="width: 100%"
            :cell-style="{ 'text-align': 'center' }"
            :header-cell-style="{ 'text-align': 'center' }"
          >
            <el-table-column prop="order_no" label="支付单号" min-width="250"></el-table-column>
            <el-table-column prop="amount" label="金额（元）"></el-table-column>
            <el-table-column prop="pay_type_desc" label="支付方式"></el-table-column>
            <el-table-column prop="status_desc" label="状态"></el-table-column>
            <el-table-column prop="createtime" label="充值时间" width="100"></el-table-column>
            <!-- <el-table-column prop="payTime" label="支付时间" width="150"></el-table-column> -->
            <el-table-column prop="operation" label="操作"></el-table-column>
          </el-table>

          <!-- 分页区域 -->
          <Pagination :obj="obj" @pagination="getPayRecord($event)" />
        </div>
      </div>
    </div>

    <!-- 对话框 -->
    <el-dialog
      title="微信扫一扫下方二维码进行充值"
      :visible.sync="dialogVisible"
      :before-close="beforeDialogClose"
      @close="dialogClose"
      width="25%"
      center
    >
      <div class="d-center flex-column dialog">
        <img :src="url" alt="" />
        <div class="bold" v-if="isMobile">注意：如果充值失败，请在电脑上打开本网站扫一扫充值，或者用另外一台手机扫码充值</div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination";
import QRCode from "qrcode";
export default {
  components: {
    Pagination,
  },
  data() {
    let validateAmount = (rule, value, callback) => {
      let reg = /^([1-9]\d*(\.\d{1,2})?|([0](\.([0][1-9]|[1-9]\d{0,1}))))$/;
      if (!reg.test(value)) {
        callback(new Error("金额必须大于0，且最多有两位小数"));
      } else {
        callback();
      }
    };
    return {
      amount: 1,
      dialogVisible: false,
      title: "",
      url: "", //生成的支付二维码
      payUrlOnMobile: "",
      isMobile: false,
      payOrderID: "",
      rechargeDesc: "",
      account: {
        balance: 0,
      },
      activeName: "first",
      payForm: {
        amount: "",
      },
      payFormRules: {
        amount: [
          { required: true, message: "请输入金额", trigger: "blur" },
          { validator: validateAmount, trigger: "blur" },
        ],
      },
      payRecord: [
        {
          payOrderID: "",
          amount: 0,
          payMethod: "",
          state: "",
          createTime: "",
          payTime: "",
          operation: "",
        },
      ],
      obj: {
        total: 0,
      },
    };
  },
  created() {
    this.getAccount();
    this.getPayRecord();
    this.getRechargeDesc();
  },
  mounted() {
    window.scrollTo(0, 0);
    this.visitOnMobile();
  },
  methods: {
    visitOnMobile2() {
      if (window.innerWidth < 1250) {
        this.isMobile = true;
      }
    },
    visitOnMobile() {
      let reg = /mobile/gi;
      if (reg.test(navigator.userAgent.toLowerCase())) {
        this.isMobile = true;
        // this.title = "点击下方充值链接进行充值";
      } else {
        // this.title = "微信扫一扫下方二维码进行充值";
      }
    },
    async getRechargeDesc() {
      const formData = new FormData();
      formData.append("label_key", "rechargeDesc");
      const { data: res } = await this.$http.post("findSysInfoByKey", formData);
      if (res.code != "0") return this.$message("获取充值说明失败");
      // console.log(res, "系统信息");
      this.rechargeDesc = res.data.label_content;
    },
    // 获取账户信息
    async getAccount() {
      const { data: res } = await this.$http.post("memberInfo");
      // console.log(res, "账户");
      if (res.code != "0") return this.$message("获取账户信息失败");
      this.account.balance = res.data.balance;
    },
    search() {
      let reg = /\S/g;
      // 若输入内容为空，禁止查询
      if (!reg.test(this.queryInfo.query)) return;
      this.getPayRecord();
    },
    // 获取充值记录
    async getPayRecord(page) {
      if (page && page.newPage) this.queryInfo.pagenum = page.newPage;
      if (page && page.newSize) this.queryInfo.pagesize = page.newSize;

      const formData = new FormData();
      formData.append("order_no", this.queryInfo.query);
      formData.append("page", this.queryInfo.pagenum);
      formData.append("rows", this.queryInfo.pagesize);
      const { data: res } = await this.$http.post("rechargeList", formData);
      // console.log(res, "充值记录");
      if (res.code != "0") {
        return this.$message("获取充值记录失败");
      }
      const arr = res.data.result;
      arr.forEach((item) => {
        item.pay_type_desc = item.pay_type == 2 ? "微信" : "支付宝";
        item.status_desc = item.status == 0 ? "成功" : "失败";
      });
      this.payRecord = arr;
      this.obj.total = res.data.totalCount;
    },
    onSubmit() {
      // console.log("submit!");
    },
    handleClick(tab, event) {
      // console.log(tab, event);
    },
    // 点击充值
    pay(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (!valid) return;
        this.loadingStart();
        let opt = this.payForm;
        const formData = new FormData();
        formData.append("amount", +opt.amount);
        const { data: res } = await this.$http.post("recharge", formData);
        // console.log(res, "充值返回");
        if (res.code != "0") {
          this.loadingEnd();
          return this.$message.error("充值失败");
        }
        this.loadingEnd();
        let self = this;
        let url = res.data.code_url;
        this.payOrderID = res.data.orderNo;
        if (this.isMobile) {
          this.payUrlOnMobile = url;
        }
        QRCode.toDataURL(url, function(err, url) {
          self.url = url;
        });
        this.dialogVisible = true;
      });
    },
    loadingStart() {
      return this.$loading({
        lock: true,
        text: "加载中",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.3)",
      });
    },
    loadingEnd() {
      this.loadingStart().close();
    },
    async dialogClose() {
      this.getAccount();
      this.getPayRecord();
      const formData = new FormData();
      formData.append("orderNo", this.payOrderID);
      const { data: res } = await this.$http.post("rechargeOrderInfo", formData);
      // console.log(res);
      if (res.data.trade_state == "SUCCESS") {
        return this.$message.success(res.data.trade_state_desc);
      }
      this.$message(res.data.trade_state_desc);
    },
    beforeDialogClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
  },
};
</script>

<style lang="scss">
.pay {
  .dialog {
    img {
      width: 50%;
      margin: auto;
    }
  }
  .el-dialog--center .el-dialog__body {
    padding: 0 25px;
  }
  padding-bottom: 200px;
  .el-form-item {
    margin-bottom: 10px;
  }
  .grid {
    border-radius: 5px;
    background-color: #fff;
    overflow: hidden;
    margin-bottom: 10px;
    .header {
      padding: 15px;
      color: #fff;
      background-image: linear-gradient(to right, #ae7000, #fed18d);
    }
    .inner {
      padding: 15px;
      .info {
        border: 1px solid #ddd;
        border-radius: 5px;
        div:nth-child(2) {
          border-bottom: 0;
        }
        > div {
          height: 40px;
          line-height: 40px;
          padding: 0 15px;
          border-bottom: 1px solid #cacaca;
        }
      }
      .el-form {
        .el-input {
          width: 200px;
        }
      }
    }
    .detail {
      padding: 10px 20px 80px;
      background-color: #e4e6ff;
      border-left: 5px solid #4250f1;
      height: 100%;
      p {
        margin-bottom: 10px;
      }
    }
  }
  .grid:nth-child(1) {
    width: 300px;
    .header {
      background-image: linear-gradient(to right, #79bd8f, #beeb9f);
    }
  }
  .grid:nth-child(2) {
    flex: 1;
    margin-left: 30px;
    .header {
      background-image: linear-gradient(to right, #7b84ed, #c6c9f1);
    }
  }
  .grid:nth-child(3) {
    width: 100%;
    .header {
      background-image: linear-gradient(to right, #7b84ed, #c6c9f1);
    }
  }
}
.el-tabs__active-bar {
  width: 72px !important;
}
</style>
